const mongoose = require('mongoose')

/*
    Schema      表
    Model       表的实例
    Documents   数据
*/
const url = `mongodb://localhost:27017/node_test`
mongoose.connect(url)

const conn = mongoose.connection

conn.on('error', () => {
    console.log('数据库连接失败')
})
conn.on('open', async () => {

    /*
        录入坐标点

        根据某个经纬度 查询最近的坐标点
    */

    const StationsSchema = mongoose.Schema({
        name: String,
        loc: Array
    })

    const StationsModel = mongoose.model('stations', StationsSchema)

    await StationsModel.deleteMany()

    await StationsModel.insertMany([
        { name: '天安门西', loc: [116.39807,39.913884] },
        { name: '天安门东', loc: [116.407988,39.91416] },
        { name: '王府井', loc: [116.418008,39.914427] },
    ])

    await StationsModel.createIndexes({ loc: '2dsphere' })

    let r = await StationsModel.find({
        loc: {
            $nearSphere: { // 查询算法
                $geometry: {
                    type: 'Point',
                    coordinates: [
                        // 地图坐标
                        116.405886,39.91398, // 天安门东附近
                    ]
                },
                $maxDistance: 1000, // 1 公里
            }
        }
    })
    console.log('最近的地铁站',r)

    /*
        const UserSchema = mongoose.Schema({
            username: {
                type: String,
                unique: true,
                index: true
            },
            pwd: String
        })

        const UserModel = mongoose.model('user', UserSchema);
        UserModel.deleteMany()

        // 曾
        let r = await UserModel.create({
            username: 'xinglong.shi',
            pwd: '123456'
        })
        console.log('add', r)
        // 删
        r = await UserModel.deleteMany({
            username: 'xinglong.shi'
        })
        console.log('delete', r)
        // 改
        r = await UserModel.updateOne(
            { username: 'xinglong.shi' },
            { $set: { pwd: 456789 } }
        )
        console.log('update', r)
        // 查
        r = await UserModel.find({ username: 'xinglong.shi' })
        console.log('query', r)
    */
})
